package com.yaorange.module.association.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yaorange.exception.BusinessException;
import com.yaorange.ma_util.util.ThreadLocalUtil;
import com.yaorange.module.association.dto.BsNewsDto;
import com.yaorange.module.association.mapper.BsNewsMapper;
import com.yaorange.module.association.service.BsNewsService;
import com.yaorange.pojo.BsNews;
import com.yaorange.response.PageResult;
import com.yaorange.response.enums.ResultCode;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class BsNewsServiceImpl implements BsNewsService {
    @Autowired
    BsNewsMapper bsNewsMapper;
    @Override
    public PageResult<BsNews> selectPage(BsNewsDto bsNewsDto) {
        if (bsNewsDto.getPageNum() == null ||bsNewsDto.getPageNum() == 0 || bsNewsDto.getPageSize() == null || bsNewsDto.getPageSize() == 0){
             throw new BusinessException(ResultCode.FAIL);
        }
        PageHelper.startPage(bsNewsDto.getPageNum(), bsNewsDto.getPageSize());
        List<BsNews> bsNewsList = bsNewsMapper.selectPage(bsNewsDto);
        PageInfo<BsNews> bsNewsPageInfo = new PageInfo<>(bsNewsList);
        PageResult<BsNews> pageResult = new PageResult<>();
        pageResult.setData(bsNewsPageInfo.getList());
        pageResult.setTotal(bsNewsPageInfo.getTotal());
        return pageResult;
    }

    @Override
    public void update(BsNews bsNews) {
        bsNews.setUpdateTime(LocalDateTime.now());
        HashMap map = (HashMap) ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("userId");
        bsNews.setUpdateBy(String.valueOf(userId));
        bsNewsMapper.update(bsNews);
    }

    @Override
    public void add(BsNews bsNews) {
        bsNews.setCreateTime(LocalDateTime.now());
        bsNews.setUpdateTime(LocalDateTime.now());
        HashMap map = (HashMap) ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("userId");
        bsNews.setUpdateBy(String.valueOf(userId));
        bsNews.setCreateBy(String.valueOf(userId));
        bsNews.setReadNum(0);
        bsNews.setDelFlag(0);
        bsNewsMapper.add(bsNews);
    }
}
